﻿layui.use(['form', 'table', 'http', 'popup', 'upload', 'drawer', 'tag', 'common'], function () {
    var form = layui.form;
    var table = layui.table;
    var layer = layui.layer;
    var $ = layui.$;
    var popup = layui.popup;
    var http = layui.http;
    var upload = layui.upload;
    var drawer = layui.drawer;
    var tag = layui.tag;
    var common = layui.common;
    var bookshelf = [];
    var codeArray = [];
    var deleteShelfId = [];
    var middle = true;
    table.render({
        elem: '#dataTable',
        url: '/Library/GetList',
        where: { name: $("#name").val() },
        height: 'full',
        page: true,
        skin: 'line',
        toolbar: '#toolbar',
        defaultToolbar: [{
            title: '刷新',
            layEvent: 'refresh',
            icon: 'layui-icon-refresh',
        }, 'filter', 'print', 'exports'],
        cols: [[
            { type: 'checkbox' },
            { field: 'name', title: '图书室' },
            { field: 'code', title: '编号' },
            { field: 'location', title: '位置' },
            { field: 'bookshelfCount', title: '书架数' },
            {
                title: '状态', templet: function (row) {
                    return '<input type="checkbox" name="enable" value="' + row.id + '" lay-skin="switch" lay-text="开室|闭室" lay-filter="isOpen" ' + (row.isOpen ? "checked" : "") + ' />';
                }
            },
            { field: 'bookCount', title: '藏书数' },
            { title: '操作', toolbar: '#rowbar' },
        ]],
        done: function (res, curr, count) {
            if (res.code === 1) {
                popup.toastError(res.msg);
            }
        }
    });

    // 表格上方的按钮
    table.on('toolbar(dataTable)', function (obj) {
        if (obj.event === 'add') {
            resetFrom();
            add();
        }
        else if (obj.event === 'refresh') {
            refresh();
        }
        else if (obj.event === 'import') {

        }
    });
    table.on('tool(dataTable)', function (obj) {
        if (obj.event === 'edit') {
            resetFrom();
            add();
            form.val("form", obj.data);
            getShelf(obj.data.id);
        }
        else if (obj.event === 'delete') {
            layer.confirm(`确定删除${obj.data.code} ${obj.data.name}?`, { icon: 3, title: '提示' }, function (index) {
                var loading = layer.load(2);
                http.ajax({
                    url: '/Library/Delete',
                    data: { Id: obj.data.id },
                    success: function (res) {
                        layer.close(loading);
                        if (res.code === 0) {
                            popup.toastSuccess(res.msg);
                            layer.close(index);
                            refresh();
                        } else {
                            popup.toastError(res.msg);
                        }
                    },
                    error: function () {
                        layer.close(loading);
                        popup.toastError("请求失败，请稍后重试");
                    }
                });

            });
          
        }

    });
    var drawerDom;
    function add() {
        drawerDom = drawer.open({
            direction: "right",
            dom: ".layer-close-mask",
            distance: "60%",
            maskClose: false
        });
    }
    $("#btnClose").click(function () {
        drawerDom.close();
    })
    /**刷新 */
    function refresh() {
        var data = { name: $("#name").val() };
        table.reload('dataTable', {
            where: data,
            page: {
                curr: 1
            }
        });
    }

    tag.on('delete(shelf)', function (data) {
        var temp = bookshelf[data.index];
        temp.id > 0 && deleteShelfId.push(temp.id);
        common.removeByIndex(bookshelf, data.index);
        common.removeByIndex(codeArray, data.index);
    });
    form.on('switch(middle)', function (data) {
        middle = data.elem.checked;
    });

    $("#createShelf").click(function () {
        if (bookshelf.length >= 26) {
            popup.toastError("书架数量范围为 1~26");
            return false;
        }
        var html = "";
        var prefix = $("#prefix").val();
        var suffix = $("#suffix").val();
        var count = parseInt($("#count").val());
        if (!count || (count > 26 || count < 1)) {
            popup.toastError("书架数量范围为 1~26");
            return false;
        }
        var tempc = 0;
        while (count > 0) {
            tempc++;
            var codes = [];
            prefix && codes.push(prefix);
            middle && codes.push(tempc);
            !middle && codes.push(String.fromCharCode(65 + tempc));
            suffix && codes.push(suffix);
            var code = codes.join("-");
            if (codeArray.indexOf(code) === -1) {
                count--;
                if (bookshelf.length < 26) {
                    codeArray.push(code);
                    html += '<span lay-id="' + tempc + '"  class="tag-item tag-item-normal">' + code + '</span>';
                    bookshelf.push({
                        id: 0,
                        code: code,
                        libraryId: $("#id").val()
                    });
                }
            }
        }
        $("#shelf").append(html);
        tag.render("shelf");
    });

    form.on('submit(submit)', function (data) {
        var loading = layer.load(2);
        data.field.isOpen = data.field.isOpen === 'on';
        data.field.bookshelfs = [];
        $.each(bookshelf, function (i, item) {
            if (item.id === 0) {
                data.field.bookshelfs.push(item);
            }
        })
        data.field.deleteShelfId = deleteShelfId;
        http.ajax({
            url: '/Library/AddOrUpdate',
            data: data.field,
            success: function (res) {
                layer.close(loading);
                if (res.code === 0) {
                    popup.toastSuccess(res.msg);
                    refresh();
                    resetFrom();
                } else {
                    popup.toastError(res.msg);
                }
            },
            error: function () {
                layer.close(loading);
                popup.toastError("请求失败，请稍后重试");
            }
        });
        return false;


    })

    $("#reset").click(function () {
        resetFrom();
    });
    function resetFrom() {
        form.val("form", {
            id: 0,
            name: '',
            code: '',
            location: '',
            isOpen: true,
            prefix: '',
            middle: true,
            suffix: '',
            count: '',
        });
        bookshelf = [];
        var temp = [];
        $.each(bookshelf, function (i, item) {
            if (item.id != 0) {
                temp.push(item);
            }
        })
        bookshelf = temp;
        codeArray = [];
        deleteShelfId = [];
        middle = true;
        $("#shelf").empty();
    }

    function getShelf(id) {
        var loading = layer.load(2);
        http.ajax({
            url: '/Bookshelf/GetList',
            type: 'GET',
            data: { libraryId: id },
            success: function (res) {
                layer.close(loading);
                var html = '';
                $.each(res, function (i, item) {
                    html += '<span lay-id="' + i + '" type="button" class="tag-item tag-item-normal">' + item.code + '</span>';
                    codeArray.push(item.code);
                    bookshelf.push(item);
                })
                $("#shelf").append(html);
                tag.render("shelf");
            },
            error: function () {
                layer.close(loading);
                popup.toastError("请求失败，请稍后重试");
            }
        });
    }
});